package com.app.twth.ui.tally.lpn;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.app.twth.BR;
import com.app.twth.R;
import com.app.twth.app.AppRouter;
import com.app.twth.base.BaseCameraPhotoActivity;
import com.app.twth.bean.FilePathListDTO;
import com.app.twth.bean.PhotoBean;
import com.app.twth.databinding.ActivityTallyLpnBinding;
import com.app.twth.ui.checkin.PhotoAdapter;
import com.app.twth.ui.tally.sku.SkuUnitDTO;
import com.app.twth.ui.tally.sku.TallyQr;
import com.app.twth.utils.EditTextUtil;
import com.app.twth.utils.ToastUtil;
import com.app.twth.utils.Utils;

import java.util.ArrayList;
import java.util.List;

public class TallyLPNActivity extends BaseCameraPhotoActivity<ActivityTallyLpnBinding, TallyLPNViewModel> {
    private String TAG = getClass().getSimpleName();

    private TallyLPNAdapter adapter;
    private TallyLPNSizeAdapter sizeAdapter;
    private TallyQr tallyQr = new TallyQr();
    private List<PhotoBean> photo1Paths = new ArrayList<>();
    private List<TalliedSku> tallyLPNList = new ArrayList<>();
    private List<TalliedSize> tallyLPNSizes = new ArrayList<>();
    private TalliedSize size;
    private int position = 0;
    private PhotoAdapter photo1Adapter;

    @Override
    protected String setTitle() {
        return "Tally(Submit)";
    }

    @Override
    protected int initViewModelId() {
        return BR.viewModel;
    }

    @Override
    protected void initData() {
        setNext(getString(R.string.submit));

        Bundle bundle = getIntent().getBundleExtra(AppRouter.K_EXTRA);
        tallyQr = (TallyQr) bundle.getSerializable("TallyQr");
        if (tallyQr.getTyp() == 2) {
            setTitle("Damage(Submit)");
        }
        binding.tvContainerNo.setText(tallyQr.getContainerNo());
        binding.tvSku.setText(tallyQr.getBarcode());
        binding.tvCtn.setText(tallyQr.getCtnQty() + "");
        binding.tvPcs.setText(tallyQr.getPcsQty() + "");
        if (tallyQr.getCtnQty() == 0) {
            binding.tvCtnHint.setVisibility(View.GONE);
            binding.tvCtn.setVisibility(View.GONE);
        }
        if (tallyQr.getPcsQty() == 0) {
            binding.tvPcsHint.setVisibility(View.GONE);
            binding.tvPcs.setVisibility(View.GONE);
        }
        binding.tvCode.requestFocus();

        adapter = new TallyLPNAdapter(this, tallyLPNList, null);
        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerview.setLayoutManager(layoutManager1);
        binding.recyclerview.setAdapter(adapter);

        sizeAdapter = new TallyLPNSizeAdapter(this, tallyLPNSizes, position -> {
            List<TalliedSize> tallyLPNSizeList = new ArrayList<>();
            for (int i =0 ; i < tallyLPNSizes.size() ; i++){
                TalliedSize talliedSize = tallyLPNSizes.get(i);
                if (i==position){
                    talliedSize.setSelect(true);
                    size  = talliedSize;
                }else {
                    talliedSize.setSelect(false);
                }
                tallyLPNSizeList.add(talliedSize);
            }
            Log.e(TAG,"position:"+position);
            tallyLPNSizes.clear();
            tallyLPNSizes.addAll(tallyLPNSizeList);
            sizeAdapter.setData(tallyLPNSizes);
        });
        GridLayoutManager lengthLayoutManager = new GridLayoutManager(mContext, 2);
        binding.rvSize.setLayoutManager(lengthLayoutManager);
        binding.rvSize.setAdapter(sizeAdapter);

        if (tallyLPNSizes==null&&tallyLPNSizes.size()==0){
            binding.tvSize.setVisibility(View.GONE);
            binding.rvSize.setVisibility(View.GONE);
        }

        photo1Paths.add(new PhotoBean());
        photo1Adapter = new PhotoAdapter(this, photo1Paths, 0, position -> {
            this.position = position;
            requestCamera("photo1");
        }, str -> {
        });
        GridLayoutManager photo1Manager = new GridLayoutManager(this, 3);
        binding.rvPhoto1.setLayoutManager(photo1Manager);
        binding.rvPhoto1.setAdapter(photo1Adapter);

        binding.tvCode.setOnEditorActionListener(EnterListenter);
    }

    @Override
    protected void initListener() {
        viewModel.fileUploadMutableLiveData.observe(this, data -> {
            Log.e(TAG, "type():" + data.getType() + ",position:" + data.getPosition());
            if (photo1Paths.size() > data.getPosition()) {
                PhotoBean photoBean = photo1Paths.get(data.getPosition());
                photoBean.setUrlImg(data.getPath());
            }

            if (data.isSubmit()) {
                submitData();
            }
        });
        viewModel.sizeListMutableLiveData.observe(this, data -> {
            if (data==null&&data.size()==0){
                binding.tvSize.setVisibility(View.GONE);
                binding.rvSize.setVisibility(View.GONE);
                return;
            }

            for (int i =0;i<tallyLPNSizes.size();i++){
                if (tallyLPNSizes.get(position).isSelect()){
                    size  = tallyLPNSizes.get(position);
                }
            }
            binding.tvSize.setVisibility(View.VISIBLE);
            binding.rvSize.setVisibility(View.VISIBLE);
            tallyLPNSizes.clear();
            tallyLPNSizes.addAll(data);
            sizeAdapter.setData(tallyLPNSizes);

        });
        viewModel.skuListMutableLiveData.observe(this, data -> {
            tallyLPNList.clear();
            tallyLPNList.addAll(data);
            adapter.setData(tallyLPNList);
        });
        viewModel.infoResultCode.observe(this, code -> {
            Intent intent = new Intent();
            setResult(RESULT_OK, intent);
            finish();
        });
        viewModel.isLoading.observe(this, b -> {
            if (b.isShow()) {
                showProgressDialog(b.getMsg());
            } else {
                dismissProgressDialog();
            }
        });
        viewModel.errorResultCode.observe(this, code -> {
            showHint((String) code);
        });
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        initScan();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unScan();
    }

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_scan:
                setScan();
                break;
            case R.id.tv_reset:
                binding.tvCode.setText("");
                bottomLayoutBinding.tvHint.setText("");
                break;
            case R.id.tv_next:
                submitData();
                break;
        }
    }

    private TextView.OnEditorActionListener EnterListenter = new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                EditTextUtil.hideInput(mContext);
                bottomLayoutBinding.tvHint.setText("");
                barcodeStr = binding.tvCode.getText().toString();
                tallyLPNList.clear();
                adapter.setData(tallyLPNList);
                viewModel.getIbLpnSkuList(barcodeStr);
            }
            return false;
        }
    };

    @Override
    public void getScanninCode() {
        super.getScanninCode();
        bottomLayoutBinding.tvHint.setText("");
        binding.tvCode.setText(barcodeStr);
        tallyLPNList.clear();
        adapter.setData(tallyLPNList);
        viewModel.getIbLpnSkuList(barcodeStr);
    }

    @Override
    protected void getImgPath(String path) {
        setPath(path);
    }

    private void setPath(String pathImage) {
        Log.e(TAG, "setPath,pathImage:" + pathImage);
        if (!pathImage.contains("http")) {//选择的图片
            String fileName = "lpnphoto";
            viewModel.fileUpload(tallyQr.getContainerNo(), fileName, pathImage, position, false, false);
        }
        PhotoBean imgUrl = new PhotoBean();
        imgUrl.setPathImg(pathImage);
        imgUrl.setUrlImg(pathImage);
        photo1Paths.add(position, imgUrl);

        if (!Utils.isEmpty(photo1Paths.get(photo1Paths.size() - 1).getPathImg())) {
            photo1Paths.add(new PhotoBean());
        }

        if (photo1Adapter != null) {
            photo1Adapter.setData(photo1Paths);
        }
    }


    private void submitData() {
        if (System.currentTimeMillis() - timeMillis < spaceTime) {//两秒内触发一次
            return;
        }
        timeMillis = System.currentTimeMillis();
        String lpn = binding.tvCode.getText().toString();
        if (Utils.isEmpty(lpn)) {
            ToastUtil.showToast("Please input inbound lpn");
            return;
        }
        
        if (tallyLPNSizes.size()>0){
//            if (size==null){
//                ToastUtil.showToast("Please Choose the Pallet Size");
//                return;
//            }
            if (size!=null){
                tallyQr.setPalletLength(size.getPalletLength());
                tallyQr.setPalletWidth(size.getPalletWidth());
                SkuUnitDTO skuUnit = tallyQr.getSkuUnit();
                if (skuUnit==null){
                    skuUnit = new SkuUnitDTO();
                }
                skuUnit.setPalletLength(size.getPalletLength());
                skuUnit.setPalletWidth(size.getPalletWidth());
                tallyQr.setSkuUnit(skuUnit);
            }
        }
        tallyQr.setIbLpn(lpn);

        List<String> lpnPathList = new ArrayList<>();
        if (photo1Paths.size() > 0) {
            for (int i = 0; i < photo1Paths.size(); i++) {
                PhotoBean photoBean = photo1Paths.get(i);
                String s = photoBean.getUrlImg();
                Log.e(TAG, "s:" + photoBean.toString());
                if (!Utils.isEmpty(s)) {
                    if (!s.contains("http")) {
                        position = i;
                        viewModel.fileUpload(tallyQr.getContainerNo(), "photo1", s, position, true, true);
                        return;
                    }
                    lpnPathList.add(s);
                } else if (!Utils.isEmpty(photoBean.getPathImg())) {
                    position = i;
                    viewModel.fileUpload(tallyQr.getContainerNo(), "photo1", photoBean.getPathImg(), position, true, true);
                    return;
                }
            }
        }
        if (lpnPathList.size() == 0) {
            ToastUtil.showToast("Please add lpn photos");
            return;
        }

        List<FilePathListDTO> filePathList = new ArrayList<>();
        FilePathListDTO lpnFilePathListDTO = new FilePathListDTO();
        lpnFilePathListDTO.setName("lpnPhoto");
        lpnFilePathListDTO.setPathList(lpnPathList);
        filePathList.add(lpnFilePathListDTO);
        tallyQr.setLpnPhotoList(filePathList);

        viewModel.tallySubmit(tallyQr);
    }

}
